package com.wephone.Student.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.wephone.Student.R;
import com.wephone.Student.bean.ZhidaoAskListResponse;
import com.wephone.Student.bean.data.ZhidaoAskData;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.PullToRefreshView;
import com.wephone.Student.util.PullToRefreshView.OnFooterRefreshListener;
import com.wephone.Student.util.PullToRefreshView.OnHeaderRefreshListener;
import com.wephone.Student.util.RoundImageView;

public class ZhidaoActivity extends BaseActivity {
	private ViewPager viewPager;
	private List<View> mSubViews = new ArrayList<View>();
	private List<ImageView> statusBarList = new ArrayList<ImageView>();
	private ListViewAdapter adapter1;
	private ListViewAdapter adapter2;
	private ListViewAdapter adapter3;
	
	private MyResponseHandler getHandler1(){
		MyResponseHandler handler = new MyResponseHandler(ZhidaoActivity.this,ZhidaoAskListResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
				if(getDataSuccess){
					ZhidaoAskListResponse res = (ZhidaoAskListResponse)response;
					
					if(adapter1.pageIdx>=res.getTotalPage() || res.getData().size()<Constants.PAGE_SIZE){
						adapter1.hasMore = false;
					}else{
						adapter1.pageIdx++;
					}
					adapter1.getResults().addAll(res.getData());
					adapter1.notifyDataSetChanged();
				}
			}
		};
		return handler;
	}
	private MyResponseHandler getHandler2(){
		MyResponseHandler handler = new MyResponseHandler(ZhidaoActivity.this,ZhidaoAskListResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
				if(getDataSuccess){
					ZhidaoAskListResponse res = (ZhidaoAskListResponse)response;
					
					if(adapter2.pageIdx>=res.getTotalPage() || res.getData().size()<Constants.PAGE_SIZE){
						adapter2.hasMore = false;
					}else{
						adapter2.pageIdx++;
					}
					adapter2.getResults().addAll(res.getData());
					adapter2.notifyDataSetChanged();
				}
			}
		};
		return handler;
	}
	private MyResponseHandler getHandler3(){
		MyResponseHandler handler = new MyResponseHandler(ZhidaoActivity.this,ZhidaoAskListResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
				if(getDataSuccess){
					ZhidaoAskListResponse res = (ZhidaoAskListResponse)response;
					
					if(adapter3.pageIdx>=res.getTotalPage() || res.getData().size()<Constants.PAGE_SIZE){
						adapter3.hasMore = false;
					}else{
						adapter3.pageIdx++;
					}
					adapter3.getResults().addAll(res.getData());
					adapter3.notifyDataSetChanged();
				}
			}
		};
		return handler;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_zhi_dao);
		
		init();
	}
	
	private void init(){
		findViewById(R.id.btn_top_right2).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				startActivity(new Intent(getApplicationContext(),ZhidaoSearchActivity.class));
			}
		});
		findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		
		viewPager = (ViewPager)findViewById(R.id.viewpager);
		statusBarList.add((ImageView)findViewById(R.id.top_bar_status_image_1));
		statusBarList.add((ImageView)findViewById(R.id.top_bar_status_image_2));
		statusBarList.add((ImageView)findViewById(R.id.top_bar_status_image_3));
		statusBarList.get(0).setTag(0);
		statusBarList.get(0).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				int idx = Integer.parseInt(arg0.getTag().toString());
				viewPager.setCurrentItem(idx, true);
			}
		});
		statusBarList.get(1).setTag(1);
		statusBarList.get(1).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				int idx = Integer.parseInt(arg0.getTag().toString());
				viewPager.setCurrentItem(idx, true);
			}
		});
		statusBarList.get(2).setTag(2);
		statusBarList.get(2).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				int idx = Integer.parseInt(arg0.getTag().toString());
				viewPager.setCurrentItem(idx, true);
			}
		});
	
		View v1 = getSubView(0);
		mSubViews.add(v1);
		View v2 = getSubView(1);
		mSubViews.add(v2);
		View v3 = getSubView(2);
		mSubViews.add(v3);
		
		viewPager.setAdapter(new ViewAdapter());
		viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			@Override
			public void onPageSelected(int arg0) {
				if(arg0==0){
					((ImageView)findViewById(R.id.top_bar_status_image_1)).setImageResource(R.drawable.zhidao_tab01_lxsknow_focused);
					((ImageView)findViewById(R.id.top_bar_status_image_2)).setImageResource(R.drawable.zhidao_tab02_lxsknow_default);
					((ImageView)findViewById(R.id.top_bar_status_image_3)).setImageResource(R.drawable.zhidao_tab03_lxsknow_default);
					if(adapter1!=null && adapter1.hasMore && adapter1.getResults().size()==0){
						findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
						RequestParams params = new RequestParams();
						params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
						params.put("Page", "1");
						params.put("PageSize", ""+Constants.PAGE_SIZE);
						HttpClient.getInstance().get(Constants.API_ZHIDAO_GET_ASK_HOT_LIST_URL, params, getHandler1());
					}
				}else if(arg0==1){
					((ImageView)findViewById(R.id.top_bar_status_image_1)).setImageResource(R.drawable.zhidao_tab01_lxsknow_default);
					((ImageView)findViewById(R.id.top_bar_status_image_2)).setImageResource(R.drawable.zhidao_tab02_lxsknow_focused);
					((ImageView)findViewById(R.id.top_bar_status_image_3)).setImageResource(R.drawable.zhidao_tab03_lxsknow_default);
					if(adapter2!=null && adapter2.hasMore && adapter2.getResults().size()==0){
						findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
						RequestParams params = new RequestParams();
						params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
						params.put("Page", "1");
						params.put("PageSize", ""+Constants.PAGE_SIZE);
						HttpClient.getInstance().get(Constants.API_ZHIDAO_GET_ASK_NEW_LIST_URL, params, getHandler2());
					}
				}else if(arg0==2){
					((ImageView)findViewById(R.id.top_bar_status_image_1)).setImageResource(R.drawable.zhidao_tab01_lxsknow_default);
					((ImageView)findViewById(R.id.top_bar_status_image_2)).setImageResource(R.drawable.zhidao_tab02_lxsknow_default);
					((ImageView)findViewById(R.id.top_bar_status_image_3)).setImageResource(R.drawable.zhidao_tab03_lxsknow_focused);
					if(adapter3!=null && adapter3.hasMore && adapter3.getResults().size()==0){
						findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
						RequestParams params = new RequestParams();
						params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
						params.put("Page", "1");
						params.put("PageSize", ""+Constants.PAGE_SIZE);
						HttpClient.getInstance().get(Constants.API_ZHIDAO_GET_ASK_IRR_LIST_URL, params, getHandler3());
					}
				}
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
		
		RequestParams params = new RequestParams();
		params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
		params.put("Page", "1");
		params.put("PageSize", ""+Constants.PAGE_SIZE);
		HttpClient.getInstance().get(Constants.API_ZHIDAO_GET_ASK_HOT_LIST_URL, params, getHandler1());
	}
	
	private class ListViewAdapter extends BaseAdapter{
		public int pageIdx = 1;
		public boolean hasMore = true;
		private List<ZhidaoAskData> results;
		
		public ListViewAdapter(List<ZhidaoAskData> results) {
			super();
			this.results = results;
		}

		public List<ZhidaoAskData> getResults() {
			return results;
		}

		@Override
		public int getCount() {
			return results.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView==null){
				convertView = getLayoutInflater().inflate(R.layout.include_zhi_dao_list_item, null);
			}
			ZhidaoAskData askData = results.get(position);
			TextView itemTitle = (TextView)convertView.findViewById(R.id.item_title_text);
			itemTitle.setText(askData.getTitle());
			TextView itemContent = (TextView)convertView.findViewById(R.id.item_content);
			itemContent.setText(askData.getContent());
			TextView itemNumText = (TextView)convertView.findViewById(R.id.item_num_text);
			itemNumText.setText(askData.getViewnum());
			
			TextView questionAskName = (TextView)convertView.findViewById(R.id.question_ask_name);
			questionAskName.setText(askData.getuInfo().getuName());
			RoundImageView itemImage = (RoundImageView)convertView.findViewById(R.id.question_ask_image);
			if(!TextUtils.isEmpty(askData.getuInfo().getuIcon())){
				DisplayImageOptions options = new DisplayImageOptions.Builder()
		        .showStubImage(R.drawable.default_user_logo)
		        .showImageOnFail(R.drawable.default_user_logo)
		        .bitmapConfig(Bitmap.Config.ARGB_8888)
		        .cacheInMemory()
		        .cacheOnDisc()
//		        .displayer(new RoundedBitmapDisplayer(1000))
		        .build();
				String endStr = askData.getuInfo().getuIcon().substring(askData.getuInfo().getuIcon().lastIndexOf("."));
				imageLoader.displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+askData.getuInfo().getuIcon().replace(endStr, "_150_150"+endStr), itemImage, options);
			}else{
				itemImage.setImageResource(R.drawable.default_user_logo);
			}
			return convertView;
		}		
	}
	
	private View getSubView(int pageIdx){
		if(pageIdx==0){
			View view = getLayoutInflater().inflate(R.layout.include_zhi_dao_sub_view_1, null);
			ListView listView = (ListView)view.findViewById(R.id.listview);
			adapter1 = new ListViewAdapter(new ArrayList<ZhidaoAskData>());
			listView.setAdapter(adapter1);
			listView.setOnItemClickListener(new ListView.OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
						long arg3) {
					Bundle bundle = new Bundle();
					bundle.putSerializable("askData", adapter1.getResults().get(arg2));
					startActivity(new Intent(getApplicationContext(),ZhidaoAnswerListActivity.class).putExtras(bundle));
				}});
			final PullToRefreshView pullToRefreshListView = (PullToRefreshView)view.findViewById(R.id.pull_refresh_listview);
			pullToRefreshListView.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
				@Override
				public void onHeaderRefresh(PullToRefreshView view) {
					adapter1.getResults().clear();
					adapter1.hasMore = true;
					adapter1.pageIdx = 1;
					
					RequestParams params = new RequestParams();
					params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
					params.put("Page", "1");
					params.put("PageSize", ""+Constants.PAGE_SIZE);
					HttpClient.getInstance().get(Constants.API_ZHIDAO_GET_ASK_HOT_LIST_URL, params, getHandler1());
				}
			});
			pullToRefreshListView.setOnFooterRefreshListener(new OnFooterRefreshListener() {
				@Override
				public void onFooterRefresh(PullToRefreshView view) {
					if(!adapter1.hasMore){
						pullToRefreshListView.onFooterRefreshComplete();
						return;
					}
					RequestParams params = new RequestParams();
					params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
					params.put("Page", ""+adapter1.pageIdx);
					params.put("PageSize", ""+Constants.PAGE_SIZE);
					HttpClient.getInstance().get(Constants.API_ZHIDAO_GET_ASK_HOT_LIST_URL, params, getHandler1());
				}
			});
			return view;
		}else if(pageIdx==1){
			View view = getLayoutInflater().inflate(R.layout.include_zhi_dao_sub_view_2, null);
			ListView listView = (ListView)view.findViewById(R.id.listview);
			adapter2 = new ListViewAdapter(new ArrayList<ZhidaoAskData>());
			listView.setAdapter(adapter2);
			listView.setOnItemClickListener(new ListView.OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
						long arg3) {
					Bundle bundle = new Bundle();
					bundle.putSerializable("askData", adapter2.getResults().get(arg2));
					startActivity(new Intent(getApplicationContext(),ZhidaoAnswerListActivity.class).putExtras(bundle));
				}});
			final PullToRefreshView pullToRefreshListView = (PullToRefreshView)view.findViewById(R.id.pull_refresh_listview2);
			pullToRefreshListView.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
				@Override
				public void onHeaderRefresh(PullToRefreshView view) {
					adapter2.getResults().clear();
					adapter2.hasMore = true;
					adapter2.pageIdx = 1;
					
					RequestParams params = new RequestParams();
					params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
					params.put("Page", "1");
					params.put("PageSize", ""+Constants.PAGE_SIZE);
					HttpClient.getInstance().get(Constants.API_ZHIDAO_GET_ASK_NEW_LIST_URL, params, getHandler2());
				}
			});
			pullToRefreshListView.setOnFooterRefreshListener(new OnFooterRefreshListener() {
				@Override
				public void onFooterRefresh(PullToRefreshView view) {
					if(!adapter2.hasMore){
						pullToRefreshListView.onFooterRefreshComplete();
						return;
					}
					RequestParams params = new RequestParams();
					params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
					params.put("Page", ""+adapter2.pageIdx);
					params.put("PageSize", ""+Constants.PAGE_SIZE);
					HttpClient.getInstance().get(Constants.API_ZHIDAO_GET_ASK_NEW_LIST_URL, params, getHandler2());
				}
			});
			return view;
		}else{
			View view = getLayoutInflater().inflate(R.layout.include_zhi_dao_sub_view_3, null);
			ListView listView = (ListView)view.findViewById(R.id.listview);
			adapter3 = new ListViewAdapter(new ArrayList<ZhidaoAskData>());
			listView.setAdapter(adapter3);
			listView.setOnItemClickListener(new ListView.OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
						long arg3) {
					Bundle bundle = new Bundle();
					bundle.putSerializable("askData", adapter3.getResults().get(arg2));
					startActivity(new Intent(getApplicationContext(),ZhidaoAnswerListActivity.class).putExtras(bundle));
				}});
			final PullToRefreshView pullToRefreshListView = (PullToRefreshView)view.findViewById(R.id.pull_refresh_listview3);
			pullToRefreshListView.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
				@Override
				public void onHeaderRefresh(PullToRefreshView view) {
					adapter3.getResults().clear();
					adapter3.hasMore = true;
					adapter3.pageIdx = 1;
					
					RequestParams params = new RequestParams();
					params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
					params.put("Page", "1");
					params.put("PageSize", ""+Constants.PAGE_SIZE);
					HttpClient.getInstance().get(Constants.API_ZHIDAO_GET_ASK_IRR_LIST_URL, params, getHandler3());
				}
			});
			pullToRefreshListView.setOnFooterRefreshListener(new OnFooterRefreshListener() {
				@Override
				public void onFooterRefresh(PullToRefreshView view) {
					if(!adapter3.hasMore){
						pullToRefreshListView.onFooterRefreshComplete();
						return;
					}
					RequestParams params = new RequestParams();
					params.put("uId", BaseActivity.getMyInfo(getApplicationContext()).getuId());
					params.put("Page", ""+adapter3.pageIdx);
					params.put("PageSize", ""+Constants.PAGE_SIZE);
					HttpClient.getInstance().get(Constants.API_ZHIDAO_GET_ASK_IRR_LIST_URL, params, getHandler3());
				}
			});
			return view;
		}
		
	}
	
	private class ViewAdapter extends PagerAdapter {
		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(mSubViews.get(arg1));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public int getCount() {
			return mSubViews.size();
		}

		@Override
		public Object instantiateItem(View arg0, int position) {
			((ViewPager) arg0).addView(mSubViews.get(position), 0);
			
			return mSubViews.get(position);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == (arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}
	}
	
}
